//
//  NetworkConnection.m
//  jboss-admin
//
//  Created by Christos Vasilakis on 03/07/2010.
//  Copyright 2010 All rights reserved.
//

#import "FetchJSONOperation.h"

@implementation FetchJSONOperation

-(id)initJSONRequestForServer:(NSString *)theHost path:(NSString *)thePath target:(id)targClass targetMethod:(SEL)targClassMethod;
{
	if (self = [super init]) {
		hostname  = theHost;
		path = thePath;
		
		targetObject = targClass;
		targetMethod = targClassMethod;
	}
	return self;
}

- (void)main {
	NSAutoreleasePool *localPool;
	@try {
		// create the autorelease pool
		localPool  = [[NSAutoreleasePool alloc] init];
		
		// see if we have been cancelled
		
		if ([self isCancelled]) return;
		
		[NSThread sleepForTimeInterval:1.0];
		
		NSDictionary *results;
		
		NSString *url = [NSString stringWithFormat:@"http://%@:8080/jboss-admin-rest/%@", @"localhost", path];
		//NSLog(url);
		
		NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:url]];
		[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
		
		NSHTTPURLResponse* response = nil; 
		NSError* error = nil; 
		NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

		[request release];
		
		if (response != nil) {
			NSInteger statusCode = [response statusCode];
			NSString *contentType = [[response allHeaderFields] objectForKey:@"Content-Type"];
			
			if (statusCode >= 200 && statusCode < 300 && [contentType hasPrefix:@"application/json"]) {
				NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
				
				results = [responseString JSONValue];
				
				[responseString release];
				
				[targetObject performSelectorOnMainThread:targetMethod withObject:results waitUntilDone:NO];
				
			} else {
				[targetObject performSelectorOnMainThread:targetMethod withObject:@"Invalid response from server" waitUntilDone:NO];
			}

		} else {
		
			[targetObject performSelectorOnMainThread:targetMethod withObject:@"Unable to contact server" waitUntilDone:NO];
		}
		
	} @catch (NSException *exception) {
		// log exception
		NSLog(@"Exception: %@", [exception reason]);
	
	} @finally {
		[localPool release];
	}

}

-(void)dealloc
{
	NSLog(@"FetchJSONOperation dealloc");
	[super dealloc];
}

@end

